package com.jaychen.spring.factory.config;

import com.jaychen.spring.core.ioc.BeanDefinition;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * BeanFactory默认实现抽象类
 *
 * @Author Jay Chen
 * @Date 2020/11/9 12:46
 */
public abstract class AbstractBeanFactory implements BeanFactory {

    private Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

    @Override
    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        Optional.ofNullable(beanDefinition).orElseThrow(() -> new NullPointerException("bean:" + beanName + " non-existent"));
        Object bean = beanDefinition.getBean();
        if (bean == null) {
            // 初始化
            try {
                bean = doCreateBean(beanDefinition);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return bean;
    }

    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        beanDefinitionMap.put(beanName, beanDefinition);
    }

    /**
     * 初始化bean
     *
     * @param beanDefinition
     * @return
     * @throws Exception
     */
    protected abstract Object doCreateBean(BeanDefinition beanDefinition) throws Exception;
}
